package dpackage;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.ArrayList;
import java.util.List;

public class AveragePriceCalculator {
    public static void main(String[] args) {
        // 指定文件路径，这里使用绝对路径
        File file = new File("D:\\CodeFiles\\JAVA\\Experiment\\Experiment04\\Experiment402deal\\商品列表.txt");

        // 输出文件的绝对路径，用于调试
        System.out.println("文件路径: " + file.getAbsolutePath());

        Map<String, List<Double>> pricesByProduct = new HashMap<>();

        try (Scanner scanner = new Scanner(file)) {
            Pattern pattern = Pattern.compile("([^,]+),(\\d+)/台");

            while (scanner.hasNextLine()) {
                String line = scanner.nextLine();
                Matcher matcher = pattern.matcher(line);
                if (matcher.find()) {
                    String product = matcher.group(1).trim();
                    double price = Double.parseDouble(matcher.group(2));

                    // 如果商品不在map中，初始化一个空列表
                    pricesByProduct.putIfAbsent(product, new ArrayList<>());
                    pricesByProduct.get(product).add(price);
                }
            }

            // 计算并输出每个商品的平均价格
            for (Map.Entry<String, List<Double>> entry : pricesByProduct.entrySet()) {
                String product = entry.getKey();
                List<Double> prices = entry.getValue();
                double total = 0;
                for (double price : prices) {
                    total += price;
                }
                double average = total / prices.size();
                System.out.printf("%s 的平均价格: %.2f 元/台\n", product, average);
            }

        } catch (FileNotFoundException e) {
            System.out.println("文件未找到: " + file.getAbsolutePath());
        }
    }
}
